<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

	public $data;

	function __construct(){
		parent::__construct();
		if(!$this->auth->checkLogin()) redirect('user/login');
		if($this->session->userdata('Accept_flg') == '0') redirect('rule/index');
	}

	public function index()
	{
		// Load model
		$this->load->model('Chucdanh_model');
		$this->load->model('Trinhdochuyenmon_model');
		$this->load->model('Info_model');
		$this->load->model('Baibao_model');
		$this->load->model('Congtrinh_model');
		$this->load->model('Giaotrinh_model');
		$this->load->model('Huongdan_model');
		// Set default value
		$this->defaultValue();
		// Set user id
		$user_id = $this->session->userdata('User_id');
		// When post data
		if($this->input->post('save')){
			// Error flag
			$error_flg = 0;
			$mess_array = array();
			// Validate post data
			$this->load->library('form_validation');
			$this->form_validation->set_rules('name', 'Full name', 'required');
			$this->form_validation->set_rules('seniority', 'seniorty', 'numeric');
			// Set value
			$this->data['info']['image'] = $this->input->post('image');
			$this->data['info']['name'] = $this->input->post('name');
			$this->data['info']['birthday'] = $this->general->convertDateFromDmyToYmd($this->input->post('birthday'));
			$this->data['info']['seniority'] = $this->input->post('seniority');
			$this->data['info']['position'] = $this->input->post('position');
			$this->data['info']['qualification'] = $this->input->post('qualification');
			// Run validate
			if ($this->form_validation->run())
			{
				// Set user_id
				$this->data['info']['user_id'] = $this->session->userdata('User_id');
				$this->data['info']['updated_date'] = date('Y-m-d H:i:s');
				// Set image data
				$config['upload_path'] = './uploads/';
				$config['allowed_types'] = 'jpg';
				$config['max_size']	= '1024';
				$config['max_width']  = '400';
				$config['max_height']  = '400';
				$this->load->library('upload', $config);
				if ( $this->upload->do_upload('image'))
				{
					//$this->data['message'] = $this->upload->display_errors();
					$data = array('upload_data' => $this->upload->data());
					//OPEN FILE AND EXTRACT DATA /CONTENT FROM IT
					$tmpName = $data['upload_data']['full_path'];
					if(file_exists($tmpName)){
						$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
						$this->data['info']['image']  = fread($fp, filesize($tmpName)); // read the temp file
						fclose($fp);
						unlink($tmpName);
					}else{
						$this->data['message'] = 'No file';
					}
				}else{
					unset($this->data['info']['image']);
					// Check exist file upload
					if(isset($_FILES['image']['size']) && $_FILES['image']['size'] > 0){
						$mess_array[] = 'Hình ảnh không hợp lệ. Chỉ chấp nhận file jpg kích thước nhỏ hơn ('.$config['max_width'].'-'.$config['max_height'].')';
						$error_flg = 1;	
					}
				}

				// Get email and password from database
				if($this->Info_model->saveInfo($this->data['info'])){
					// Save bai bao
					$baibao = $this->createDataBaiBao($this->input->post('baibao'));
					if(!$this->Baibao_model->save($baibao, $this->data['info']['user_id'])){ $mess_array[] = 'Bài báo lưu không thành công!'; $error_flg = 1; }
					// Save cong trinh
					$congtrinh = $this->createDataCongTrinh($this->input->post('congtrinh'));
					if(!$this->Congtrinh_model->save($congtrinh, $this->data['info']['user_id'])){ $mess_array[] = 'Công trình lưu không thành công!';$error_flg = 1; }
					// Save giao trinh
					$giaotrinh = $this->createDataGiaoTrinh($this->input->post('giaotrinh'));
					if(!$this->Giaotrinh_model->save($giaotrinh, $this->data['info']['user_id'])){ $mess_array[] = 'Giáo trình lưu không thành công!'; $error_flg = 1; }
					// Save huongdan
					$huongdan = $this->createDataHuongDan($this->input->post('huongdan'));
					if(!$this->Huongdan_model->save($huongdan, $this->data['info']['user_id'])){ $mess_array[] = 'Hướng dẫn lưu không thành công!'; $error_flg = 1; }
					
					// Luu thanh cong
					if($error_flg == 0) $mess_array[]= 'Đã lưu thành công';
					// Set message
					$this->session->set_flashdata('message', $mess_array);
					redirect('home');
				}else{
					$this->data['message'] = 'Lưu không thành công';
				}

			}
		}else{
			$data = $this->Info_model->getInfo($user_id);
			if($data){
				// Set value
				$this->data['chucdanh']['selected_value'] = $data[0]->position;
				$this->data['qualification']['selected_value'] = $data[0]->qualification;
				$this->data['info']['image'] = $data[0]->image;
				$this->data['info']['name'] = $data[0]->name;
				$this->data['info']['birthday'] = $data[0]->birthday;
				$this->data['info']['seniority'] = $data[0]->seniority;
				$this->data['info']['qualification'] = $data[0]->qualification;
				// Get bai bao
				$baibao = $this->Baibao_model->getAllByUserId($user_id);
				$this->data['baibao'] = ($baibao)?$baibao:$this->data['baibao'];
				// Get cong trinh
				$congtrinh = $this->Congtrinh_model->getAllByUserId($user_id);
				$this->data['congtrinh'] = ($congtrinh)?$congtrinh:$this->data['congtrinh'];
				// Get giao trinh
				$giaotrinh = $this->Giaotrinh_model->getAllByUserId($user_id);
				$this->data['giaotrinh'] = ($giaotrinh)?$giaotrinh:$this->data['giaotrinh'];
				// Get huong dan
				$huongdan = $this->Huongdan_model->getAllByUserId($user_id);
				$this->data['huongdan'] = ($huongdan)?$huongdan:$this->data['huongdan'];

			}
		}

		$this->template->write_view('content', 'home/index',$this->data);
		$this->template->render();
	}

	function defaultValue(){
		// option Chuc Danh
		$this->data['chucdanh']['option'] = $this->Chucdanh_model->getChucDanh();
		$this->data['chucdanh']['selected_value'] = '';
		// Trinh do chuyen mon
		$this->data['qualification']['option'] = $this->Trinhdochuyenmon_model->getAll();
		$this->data['qualification']['selected_value'] = '';
		// Set value defaul
		$this->data['info']['image'] = '';
		$this->data['info']['name'] = '';
		$this->data['info']['birthday'] = date('d/m/Y');
		$this->data['info']['seniority'] = '';
		$this->data['info']['position'] = '';
		$this->data['info']['qualification'] = '';
		// Bai bao
		$this->data['baibao'][0] = $this->newBaiBao();
		// Cong trinh
		$this->data['congtrinh'][0] = $this->newCongTrinh();
		// Giao trinh
		$this->data['giaotrinh'][0] = $this->newGiaoTrinh();
		// Huong dan
		$this->data['huongdan'][0] = $this->newHuongDan();
	}
	
	function createDataBaiBao($baibao){
		if(!is_array($baibao)) return array();
		$user_id = $this->session->userdata('User_id');
		$results = array();
		foreach($baibao as $k => $v){
			if($v != NULL){
				$results[$k]['user_id'] = $user_id;
				$results[$k]['ten'] = $v;
			}
		}
		return $results;
	}
	
	function createDataCongTrinh($congtrinh){
		if(!is_array($congtrinh)) return array();
		$user_id = $this->session->userdata('User_id');
		$results = array();
		foreach($congtrinh as $k => $v){
			if($v != NULL){
				$results[$k]['user_id'] = $user_id;
				$results[$k]['ten'] = $v;
			}
		}
		return $results;
	}
	
	function createDataGiaoTrinh($giaotrinh){
		if(!is_array($giaotrinh)) return array();
		$user_id = $this->session->userdata('User_id');
		$results = array();
		foreach($giaotrinh as $k => $v){
			if($v != NULL){
				$results[$k]['user_id'] = $user_id;
				$results[$k]['ten'] = $v;
			}
		}
		return $results;
	}
	
	function createDataHuongDan($huongdan){
		if(!is_array($huongdan)) return array();
		$user_id = $this->session->userdata('User_id');
		$results = array();
		$i = 0;
		foreach($huongdan as $k => $v){
			if(trim($v['hoten']) != NULL || trim($v['detai']) != NULL){
				
				$results[$i]['user_id'] = $user_id;
				$results[$i]['hoten'] = $v['hoten'];
				$results[$i]['detai'] = $v['detai'];
				$results[$i]['from'] = $this->general->convertDateFromDmyToTime($v['from']);
				$results[$i]['to'] = $this->general->convertDateFromDmyToTime($v['to']);
				
				$i++;
			}
		}
		return $results;
	}
	
	function newBaiBao(){
		$data = new Baibao_model();
		$data->id = 0;
		$data->ten = '';
		return $data;
	}
	
	function newCongTrinh(){
		$data = new Congtrinh_model();
		$data->id = 0;
		$data->ten = '';
		return $data;
	}
	
	function newGiaoTrinh(){
		$data = new Giaotrinh_model();
		$data->id = 0;
		$data->ten = '';
		return $data;
	}
	
	function newHuongDan(){
		$data = new HuongDan_model();
		$data->id = 0;
		$data->hoten = '';
		$data->detai = '';
		$data->from = NULL;
		$data->to = NULL;
		return $data;
	}
	
	
}